import Vue from "vue";
import Vuex from "vuex";
import {getTipTypeList, getTipTypesByCount} from "@/api/api";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    logo: '',
    customerMessageList: [],
    Authorization: null,
    deptList: [],
    me: null,
    myName: "",
    websocket: null,
    myGoodTips: [],
    unreadMessages: {},
    tipTypeList: [], // 存储帖子类型列表
  },
  mutations: {
    addlogo(state, logo) {
      state.logo = logo;
    },
    incrementUnread(state, userEmail) {
      if (!userEmail) return;
      const count = state.unreadMessages[userEmail] || 0;
      Vue.set(state.unreadMessages, userEmail, count + 1);
      if (state.myName) {
        localStorage.setItem(state.myName + 'unreadMessages', JSON.stringify(state.unreadMessages));
      }
    },
    markAsRead(state, userEmail) {
      if (!userEmail) return;
      Vue.set(state.unreadMessages, userEmail, 0);
      if (state.myName) {
        localStorage.setItem(state.myName + 'unreadMessages', JSON.stringify(state.unreadMessages));
      }
    },
    addUserMessage(state, content) {
      state.customerMessageList.push({
        id: Date.now(),
        text: content,
        from: 'user',
        isStreaming: false
      });
    },
    addEVAMessage(state, payload) {
      state.customerMessageList.push({
        id: payload.id,
        text: payload.text || '',
        from: 'eva',
        isStreaming: payload.isStreaming || false
      });
    },
    appendToEVAMessage(state, payload) {
      const msg = state.customerMessageList.find(m =>
          m.id === payload.id && m.from === 'eva'
      );
      if (msg) {
        msg.text += payload.content;
      }
    },
    setMyGoodTips(state, tips) {
      state.myGoodTips = tips;
      if (state.myName) {
        sessionStorage.setItem(state.myName + 'myGoodTips', JSON.stringify(tips));
      }
    },
    setDeptList(state, list) {
      state.deptList = list;
      if (state.myName) {
        sessionStorage.setItem(state.myName + 'deptList', JSON.stringify(list));
      }
    },
    setTipTypeList(state, list) {
      state.tipTypeList = list;
      if (state.myName) {
        sessionStorage.setItem(state.myName + 'tipTypeList', JSON.stringify(list));
      }
    },
    setToken(state, token) {
      state.Authorization = token;
      if (state.myName) {
        sessionStorage.setItem(state.myName + 'Authorization', JSON.stringify(token));
      }
    },
    setMyName(state, name) {
      state.myName = name;
      // 初始化需要用户名前缀的状态
      state.Authorization = JSON.parse(sessionStorage.getItem(name + 'Authorization') || 'null');
      state.deptList = JSON.parse(sessionStorage.getItem(name + 'deptList') || '[]');
      state.myGoodTips = JSON.parse(sessionStorage.getItem(name + 'myGoodTips') || '[]');
      state.unreadMessages = JSON.parse(localStorage.getItem(name + 'unreadMessages') || '{}');
      state.tipTypeList = JSON.parse(sessionStorage.getItem(name + 'tipTypeList') || '[]');
    },
    updateCustomerMessageInStore(state, payload) {
      state.customerMessageList = [...state.customerMessageList, payload];
    },
    clearMessages(state) {
      state.customerMessageList = [];
    },
    updateMessageText(state, { index, text }) {
      if (state.customerMessageList[index]) {
        state.customerMessageList[index].text = text;
      }
    },
  },
  getters: {
    unreadCount: (state) => (userEmail) => {
      return state.unreadMessages[userEmail] || 0;
    },
    totalUnreadCount: (state) => {
      return Object.values(state.unreadMessages).reduce((acc, count) => acc + count, 0);
    },
    isLoggedIn: (state) => {
      return !!state.Authorization;
    },
  },
  actions: {
    login({ commit, dispatch }, { username, token }) {
      // 设置用户名
      commit('setMyName', username);
      // 设置token
      commit('setToken', token);
      // 同时将token存储在localStorage中，以便http请求拦截器使用
      localStorage.setItem('Authorization', token);
      // 获取帖子类型列表
      dispatch('fetchTipTypes');
    },

    // 初始化认证状态
    initAuth({ state, commit, dispatch }) {
      // 如果已经有认证信息，则获取帖子类型列表
      if (state.Authorization) {
        dispatch('fetchTipTypes');
      }
    },

    // 获取帖子类型列表
    async fetchTipTypes({ commit }) {
      try {
        const response = await getTipTypeList();

        if (response.data && response.data.data && response.data.data.list) {
          commit('setTipTypeList', response.data.data.list);
        }
      } catch (error) {
        console.error('获取帖子类型失败:', error);
      }
    },
  },
});
